package binaryTreeSearch;

public class BinaryTreeSearch {
    static class TreeNode {
        public TreeNode left;
        public TreeNode right;

        public int val;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root;

    // 查询
    public boolean search(int key) {
        TreeNode cur = root;

        while(cur != null) {
            if(cur.val == key) {
                return true;
            } else if(cur.val > key) {
                cur = cur.left;
            } else {
                cur = cur.right;
            }
        }

        return false;
    }

    // 添加
    public boolean insert(int val) {
        TreeNode node = new TreeNode(val);
        if(root == null) {
            root = node;
            return true;
        }

        TreeNode cur = root;
        TreeNode parent = null;

        while(cur != null) {
            if(cur.val == val) {
                return false;
            } else if(cur.val > val) {
                parent = cur;
                cur = cur.left;
            } else {
                parent = cur;
                cur = cur.right;
            }
        }

        // 此时一定找不到与 val 相同的 TreeNode 的值
        if(parent.val > val) {
            // val 比较小
            parent.left = node;
        } else {
            parent.right = node;
        }

        return true;
    }

    // 删除
    public void remove(int key) {

        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null) {
            if(cur.val == key) {
                break;
            } else if(cur.val > key) {
                parent = cur;
                cur = cur.left;
            } else {
                parent = cur;
                cur = cur.right;
            }
        }
        if(cur == null) {
            return;
        }

        if(cur.left == null) {
            if(cur == root) {
                root = cur.right;
            } else if(parent.left == cur) {
                parent.left = cur.right;
            } else {
                parent.right = cur.right;
            }
        } else if(cur.right == null) {
            if(cur == root) {
                root = cur.left;
            } else if(parent.left == cur) {
                parent.left = cur.left;
            } else {
                parent.right = cur.left;
            }
        } else {
            // cur 有两颗 树 用替换法
            // 找到右树的最小值
            TreeNode targetParent = cur;
            TreeNode target = cur.right;
            while(target.left != null) {
                targetParent = target;
                target = target.left;
            }
            // 此时 target 指向的是大于 cur.val 的第一个值
            cur.val = target.val;
            if(targetParent.right == target) {
                // 考虑到一次都没有换 --> 也就是 target 在 parent 右侧
                targetParent.right = target.right;
            } else {
                targetParent.left = target.right;
            }
        }
    }
}
